//
//  CustomSwitchView1.swift
//  MoyoungCommon
//
//  Created by 易先生 on 2022/10/25.
//

import UIKit
import MYModule

public protocol CustomSwitchViewDelegate : NSObjectProtocol {
    func switchAction(isOn:Bool)
}

public class CustomSwitchView: UIControl {
    
    open var delegate : CustomSwitchViewDelegate?
    
    open var onTintColor : UIColor = UIColor.theme
    
    open var inactiveColor : UIColor = UIColor.assist_D0D0D0
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        makeUI()
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func makeUI() {
        self.layer.cornerRadius = 15

        self.addSubview(switchButton)
        
        self.setOn(isOn: false)
        
        self.addTarget(self, action: #selector(bgAction), for: .touchUpInside)
    }
    
    public func setOn(isOn:Bool) {
        switchButton.isSelected = isOn
        guard isOn else {
            switchButton.snp.remakeConstraints { make in
                make.leading.equalToSuperview().offset(1)
                make.size.equalTo(CGSize(width: 28, height: 28))
                make.centerY.equalToSuperview()
            }
            self.backgroundColor = inactiveColor
            return
        }
        switchButton.snp.remakeConstraints { make in
            make.trailing.equalToSuperview().offset(-1)
            make.size.equalTo(CGSize(width: 28, height: 28))
            make.centerY.equalToSuperview()
            self.backgroundColor = onTintColor
        }
    }
    
    @objc private func bgAction() {
        switchButton.isSelected = !switchButton.isSelected
        setOn(isOn: switchButton.isSelected)
        delegate?.switchAction(isOn: switchButton.isSelected)
    }
    
    @objc private func switchAction(sender:Button) {
        sender.isSelected = !sender.isSelected
        setOn(isOn: sender.isSelected)
        delegate?.switchAction(isOn: sender.isSelected)
    }
    
    private lazy var switchButton: Button = {
        let switchButton = Button()
        switchButton.setImage(UIImage(named: "ic_switch_off"), for: .normal)
        switchButton.setImage(UIImage(named: "ic_switch_on"), for: .selected)
        switchButton.addTarget(self, action: #selector(switchAction(sender:)), for: .touchUpInside)
        return switchButton
    }()

}
